package com.example.roam.ui.activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.roam.R;
import com.example.roam.game.emeimountain.game.model.fin.GameInfoLayer;
import com.example.roam.model.gson.Verify;
import com.example.roam.utils.Constans;
import com.example.roam.utils.DBHelper;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.Md5Util;
import com.example.roam.utils.StatusBarUtils;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;

import static com.example.roam.ui.activity.LoginActivity.isEmail;
import static com.example.roam.utils.Constans.account_select;
//注册页
public class RegisterActivity extends AppCompatActivity {
    private Button btncode;
    private Button btnback;
    private EditText edit1;
    private EditText edit2;
    private EditText edit3;
    private EditText edit4;
    private static final String TAG = "RegisterActivity";
    boolean a = true;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    int result = msg.arg1;
                    String sessionId = msg.obj.toString();
                    //邮箱或者密码错误
                    if (result == 0) {
                        Toast.makeText(RegisterActivity.this, "请输入正确的邮箱和密码", Toast.LENGTH_SHORT).show();
                    } else if (result == 1) {
                        //使用SharePreferences保存
                        SharedPreferences preferences = getSharedPreferences("config", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        //保存sessionId
                        editor.putString("cookie", sessionId);
                        //执行修改
                        editor.commit();
                        //将登录从堆栈清除
                        RegisterActivity.this.finish();
                    }
                    break;
                case 2:
                    Toast.makeText(RegisterActivity.this,
                            "正在连接中", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色

        initView();
        initEvent();
        initData();
    }

    private void initView() {
        edit1 = (EditText) findViewById(R.id.edit1);
        edit2 = findViewById(R.id.edit2);
        edit3 = findViewById(R.id.edit3);
        edit4 = findViewById(R.id.edit4);
        btncode =findViewById(R.id.btncode2);
        btnback = findViewById(R.id.btnback2);
    }

    private void initData(){
        edit1.setText("1215447720@qq.com");
        edit2.setText("123123");
        edit3.setText("123123");
    }

    /**
     * roamcat1@126.com
     * 123123
     * */
    public void initEvent(){
        btncode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = edit1.getText().toString();
                boolean judge = isEmail(email);
                if (judge == true) {
//                    注册！
                    String url = "http://47.108.249.115:8080/LuShuDao0.0.2-1.0-SNAPSHOT/UserInfo/addUser";
                    String userAcc = edit1.getText().toString().trim();
                    String userPassword = edit2.getText().toString().trim();
                    try {
                        userPassword = Md5Util.encodeByMd5(userPassword+ Constans.SALT);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//                    Log.i(TAG, "onClick: register -> userAcc "+userAcc+" userPassword"+userPassword);
                    FormBody formBody = new FormBody.Builder().add("userAcc",userAcc).add("userPwd",userPassword).build();
                    HttpUtil.getPostResponse(url, formBody, new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Toast.makeText(RegisterActivity.this,"密码不正确！",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            Log.i(TAG, "onResponse: "+response.body().string());
                            //                            发送邮箱验证码
                            String codeUrl = "http://47.108.249.115:8080/ShuDao0.0.2-1.0-SNAPSHOT/email/put?tomail="+edit1.getText().toString();
                            HttpUtil.getGetResponse(codeUrl, new Callback() {
                                @Override
                                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                                }

                                @Override
                                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                    RegisterActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(RegisterActivity.this,"验证码已发送！",Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            }
        });

        btnback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String email = edit1.getText().toString();
                String password = edit2.getText().toString();
                String password1 = edit3.getText().toString();
                boolean judge = isEmail(email);
                if (judge == true) {
                    if (!email.isEmpty() && !password.isEmpty() && password1.equals(password)) {
//                       验证邮箱
                        String patternEmailUrl = "http://47.108.249.115:8080/ShuDao0.0.2-1.0-SNAPSHOT/email/verify";
                        FormBody formBody = new FormBody.Builder().add("inNumber",edit4.getText().toString()).build();
                        HttpUtil.getPostResponse(patternEmailUrl, formBody, new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                String string = response.body().string();
                                RegisterActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Verify verify = new Gson().fromJson(string, Verify.class);
                                        if( verify.isSuccess() ){
                                            Toast.makeText(RegisterActivity.this,"注册成功！",Toast.LENGTH_SHORT).show();
                                            new Thread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        Thread.sleep(1000);
                                                    } catch (InterruptedException e) {
                                                        e.printStackTrace();
                                                    }
                                                    RegisterActivity.this.runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
                                                            startActivity(intent);
                                                        }
                                                    });
                                                }
                                            }).start();
                                        }
                                    }
                                });
                            }
                        });


                    } else if (!password.equals(password1)) {
                        Toast.makeText(getApplicationContext(), "两次密码输入不一致", Toast.LENGTH_LONG).show();
                    } else if (password.isEmpty()) {
                        Toast.makeText(getApplicationContext(), "密码不能为空", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(RegisterActivity.this, "请输入正确的邮箱", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    // 注册时，往user表内插入数据
    public void insertUserTable() {
        DBHelper dbHelper = new DBHelper(RegisterActivity.this, null, null, 1);
        SQLiteDatabase ds = dbHelper.getReadableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("u_account", edit1.getText().toString());
        contentValues.put("u_password", edit2.getText().toString());
        contentValues.put("account_select", account_select);
        Cursor cursor = ds.rawQuery("select * from user where u_account=?", new String[]{edit1.getText().toString()});
        if (cursor.getCount() > 0) {
            Toast.makeText(RegisterActivity.this, "用户已存在", Toast.LENGTH_LONG).show();
        } else {
            Constans.u_account = edit1.getText().toString();
            Constans.u_password = edit2.getText().toString();
            ds.insert("user", null, contentValues);
            Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            startActivity(intent);
        }
    }
}